package com.example.weather.util;

import java.math.BigDecimal;
import java.nio.charset.Charset;
import java.text.NumberFormat;
import java.util.*;

/**
 * @author mengxianqian
 * @since 2019/7/17 16:51
 */
public class StringUtil {

    public static final String ENCODING_DEFAULT = "UTF-8";

    /**
     * 转义
     * @param src 源字符串
     * @return
     */
    public static String escape(String src) {
        if(src==null){
            return "";
        }
        int i;
        char j;
        StringBuilder tmp = new StringBuilder();
        tmp.ensureCapacity(src.length() * 6);
        for (i = 0; i < src.length(); i++) {
            j = src.charAt(i);
            if (Character.isDigit(j) || Character.isLowerCase(j)
                    || Character.isUpperCase(j)){
                tmp.append(j);
            }else if (j < 256) {
                tmp.append("%");
                if (j < 16){
                    tmp.append("0");
                }
                tmp.append(Integer.toString(j, 16));
            } else {
                tmp.append("%u");
                tmp.append(Integer.toString(j, 16));
            }
        }
        return tmp.toString();
    }

    /**
     * 还原转义字符串
     * @param src
     * @return
     */
    public static String unescape(String src) {
        StringBuilder tmp = new StringBuilder();
        tmp.ensureCapacity(src.length());
        int lastPos = 0;
        int pos;
        char ch;
        while (lastPos < src.length()) {
            pos = src.indexOf('%', lastPos);
            if (pos == lastPos) {
                if (src.charAt(pos + 1) == 'u') {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 2, pos + 6), 16);
                    tmp.append(ch);
                    lastPos = pos + 6;
                } else {
                    ch = (char) Integer.parseInt(src
                            .substring(pos + 1, pos + 3), 16);
                    tmp.append(ch);
                    lastPos = pos + 3;
                }
            } else {
                if (pos == -1) {
                    tmp.append(src.substring(lastPos));
                    lastPos = src.length();
                } else {
                    tmp.append(src.substring(lastPos, pos));
                    lastPos = pos;
                }
            }
        }
        return tmp.toString();
    }

    public static String paserNull(Object str){
        if(str == null){
            return "";
        }
        return String.valueOf(str).trim();
    }

    public static String[] convertObjArray(Object[] array){
        if(array == null){
            return new String[0];
        }
        return Arrays.stream(array).map(Object::toString).toArray(String[] :: new);
    }
    /**
     * 随机字符串
     * @param prefix 前缀
     * @param len 长度
     * @return 随机字符串
     */
    public static String randomCode(String prefix, int len){
        return prefix + randomCode(len);
    }

    /**
     * 随机字符串
     * @param len 长度
     * @return 随机字符串
     */
    public static String randomCode(int len){
        final int maxNum = 10;
        // 生成的随机数
        int i;
        // 生成的密码的长度
        int count = 0;
        char[] str = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k',
                'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w',
                'x', 'y', 'z','A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K',
                'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
                'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

        StringBuilder pwd = new StringBuilder("");
        Random r = new Random();
        while (count < len) {
            // 生成随机数，取绝对值，防止生成负数
            // 生成的数最大为36-1
            i = Math.abs(r.nextInt(maxNum));

            if (i >= 0 && i < str.length) {
                pwd.append(str[i]);
                count++;
            }
        }

        return pwd.toString();
    }
    /**
     * 截断字符串
     * @param str 源字符串
     * @param bytelength 字节长度
     * @param sufix 后缀
     * @return
     */
    public static String truncate(String str, int bytelength, String sufix) {
        if (str == null) {
            return null;
        }
        if (bytelength <= 0) {
            return "";
        }
        if (str.getBytes(Charset.forName(ENCODING_DEFAULT)).length <= bytelength) {
            return str;
        }
        StringBuilder buff = new StringBuilder();

        int index = 0;
        char c;
        while (bytelength > 0) {
            c = str.charAt(index);
            if (c < 128) {
                bytelength--;
            } else {
                // GBK编码汉字占2字节，其他编码的不一样，要修改下面几句
                bytelength--;
                // 被截断了
                if (bytelength < 1) {
                    break;
                }
                bytelength--;
            }
            buff.append(c);
            index++;
        }
        buff.append(sufix);
        return buff.toString();
    }

    /**
     * 字符串转布尔值
     * @param boolStr
     * @return
     */
    public static boolean parseBoolean(String boolStr) {
        return "true".equals(boolStr) || "1".equals(boolStr);
    }

    /**
     * 转换字符串编码 iso到utf8
     * @param isostr
     * @return
     */
    public static String iso2uft8(String isostr) {
        try {
            byte[] byteStr = isostr.getBytes("ISO-8859-1");
            return new String(byteStr, ENCODING_DEFAULT);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 转换字符串编码 gbk到iso
     * @param gbkstr
     * @return
     */
    public static String gbk2iso(String gbkstr) {
        try {
            byte[] byteStr = gbkstr.getBytes("GB2312");
            return new String(byteStr, "ISO-8859-1");
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 拼接字符串
     * @param list
     * @param separator
     * @return
     */
    public static String join(List<?> list, String separator) {
        return org.apache.commons.lang3.StringUtils.join(list, separator);
    }

    /**
     * 拼接字符串
     * @param list
     * @param separator
     * @param warpper
     * @return
     */
    public static String join(List<?> list, String separator, String warpper) {
        return join(list.toArray(),separator,warpper);
    }

    /**
     * 拼接字符串
     * @param list
     * @param separator 连接符
     * @return
     */
    public static String join(Object[] list, String separator) {
        return org.apache.commons.lang3.StringUtils.join(list, separator);
    }

    /**
     * 拼接字符串
     * @param list
     * @param separator 分割符
     * @param warpper 包裹符
     * @return
     */
    public static String join(Object[] list, String separator, String warpper) {
        List<String> warpperList = new ArrayList<>();
        for(Object o : list){
            warpperList.add(warpper+o+warpper);
        }
        return org.apache.commons.lang3.StringUtils.join(warpperList, separator);
    }

    public static boolean isNotEmpty(String str){
        return org.apache.commons.lang3.StringUtils.isNotEmpty(str);
    }

    public static boolean isNotEmpty(Object str){
        return str!= null && isNotEmpty(str.toString());
    }

    public static boolean isEmpty(Object str){
        return str == null || isEmpty(str.toString());
    }
    public static boolean isEmpty(String str){
        return org.apache.commons.lang3.StringUtils.isEmpty(str);
    }
    public static boolean isBlank(String str){
        return org.apache.commons.lang3.StringUtils.isBlank(str);
    }
    public static boolean isNotBlank(String str){
        return org.apache.commons.lang3.StringUtils.isNotBlank(str);
    }

    public static String warpper(String str, String warpper){
        String result = "";
        if(isNotEmpty(str) && isNotEmpty(warpper)){
            result = warpper+str+warpper;
        }
        return result;
    }

    /**
     * 分割字符串
     * @param src
     * @param separator 分割符
     * @return
     */
    public static String[] split(String src, String separator) {
        return org.apache.commons.lang3.StringUtils.split(src,separator);
    }

    /**
     * 分割后再拼接字符串
     * @param src
     * @param srcSeparator 分割符
     * @param separator 拼接符
     * @return
     */
    public static String split4join(String src, String srcSeparator, String separator) {
        return join(split(src,srcSeparator),separator);

    }

    /**
     * 判断字符串中是否含有中文
     * @param str
     * @return
     */
    public Boolean isIncludeChinese(String str){
        return str.getBytes(Charset.forName(ENCODING_DEFAULT)).length != str.length();
    }

    public static String replaceIllegalChar(String s){
        s = s == null ? "" : s;
        s = s.replaceAll("\'", "\'\'");
        s = s.replaceAll("_", "\\_");
        s = s.replaceAll("%", "\\%");
        return s;
    }

    public static String uuid(){
        UUID uuid = UUID.randomUUID();
        return uuid.toString();
    }

    /**
     * Convert string to decimal.
     * strNum == null || empty string returns 0
     *
     * @param strNum 			- String representation of a number
     * @return BigDecimal
     */
    public static BigDecimal getDecimalValue(String strNum){
        if(isEmpty(strNum)){
            return new BigDecimal("0");
        }
        return new BigDecimal(strNum.replaceAll(",", ""));
    }

    public static String intArrToStr(int[] arr) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < arr.length - 1; i++) {
            sb.append(String.valueOf(arr[i]));
            sb.append(";");
        }
        sb.append(arr[arr.length - 1]);
        return sb.toString();
    }

    public static int[] strArrToIntArr(String[] strArr) {
        int[] intArr = new int[strArr.length];
        for (int i = 0; i < strArr.length; i++) {
            intArr[i] = Integer.parseInt(strArr[i]);
        }
        return intArr;
    }

    /**
     * 将数字格式化成百分号的格式（保留两位小数）
     * @param value 数字
     * @return 格式化的字符串
     */
    public static String formatPercent(double value){
        NumberFormat percent = NumberFormat.getPercentInstance();
        percent.setMaximumFractionDigits(2);
        return percent.format(value);
    }

}
